package com.party.course.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.hutool.core.date.DateUtil;
import com.party.business.domain.TOrder;
import com.party.common.core.domain.entity.SysRole;
import com.party.common.core.domain.entity.SysUser;
import com.party.common.utils.PageUtils;
import com.party.common.utils.StringUtils;
import com.party.course.domain.*;
import com.party.course.eumn.SubAmount;
import com.party.course.mapper.CoachInfoMapper;
import com.party.course.mapper.PayGroupMapper;
import com.party.course.mapper.PlanClassMapper;
import com.party.course.service.IApprovalInfoService;
import com.party.course.util.ReceiverModel;
import com.party.course.util.SendQWmsgUtil;
import com.party.course.util.XunpayUtil;
import com.party.system.mapper.SysRoleMapper;
import com.party.system.mapper.SysUserMapper;
import com.party.system.service.impl.SysLogininforServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.party.course.mapper.StudentInfoMapper;
import com.party.course.service.IStudentInfoService;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.party.common.utils.SecurityUtils;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import static java.awt.SystemColor.info;

/**
 * 学员信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-29
 */
@Service
public class StudentInfoServiceImpl extends ServiceImpl<StudentInfoMapper, StudentInfo> implements IStudentInfoService {
    @Resource
    private StudentInfoMapper studentInfoMapper;
    @Resource
    private PayGroupMapper payGroupMapper;
    @Resource
    private CoachInfoMapper coachInfoMapper;
    @Resource
    private PlanClassMapper planClassMapper;
    @Resource
    private IApprovalInfoService approvalInfoService;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysLogininforServiceImpl sysLogininforService;

    /**
     * 查询学员信息
     *
     * @param id 学员信息主键
     * @return 学员信息
     */
    @Override
    public StudentInfo view(String id) {
        StudentInfo info = studentInfoMapper.selectStudentInfoById(id);
        String orderCode = info.getOrderCode();

        int teachSection = Integer.parseInt(info.getTeachSection());
        int level = Integer.parseInt(info.getClassLevel());
        String isTest = info.getIsTest();
        if("1".equals(isTest)){
            // 合伙人分账金额
            BigDecimal hhramount = SubAmount.getAmountByCondition(teachSection, level, 3, 0);
            info.setHhrAmount(hhramount);
            System.out.println("合伙人分账金额"+hhramount);
            BigDecimal amount = SubAmount.getAmountByCondition(teachSection, level, 9, 9);
            info.setAmount(amount);
            if(StringUtils.isNotEmpty(info.getStoreUserId())){
                SysUser user = sysUserMapper.selectUserById(Long.parseLong(info.getStoreUserId()));
                if (ObjectUtil.isNotEmpty(user)) {
                    info.setHhrName(user.getUserName());
                }
            }
        }else {
            info.setAmount(new BigDecimal("39.9"));
            if(StringUtils.isNotEmpty(info.getStoreUserId())){
                SysUser user = sysUserMapper.selectUserById(Long.parseLong(info.getStoreUserId()));
                if (ObjectUtil.isNotEmpty(user)) {
                    info.setHhrName(user.getUserName());
                }
            }
        }
        setNames(info);
        return info;
    }

    /**
     * 查询学员信息列表
     *
     * @param studentInfo 学员信息
     * @return 学员信息
     */
    @Override
    public List<StudentInfo> findList(StudentInfo studentInfo) {
        Long userId = SecurityUtils.getUserId();
        String roleId = sysLogininforService.findLoginRoleId(userId.toString());
        //用于小程序查询列表
        if (StrUtil.isNotEmpty(studentInfo.getIsCoach())) {
            CoachInfo coachInfo = coachInfoMapper.findByUserId(userId.toString());
            if ("0".equals(studentInfo.getIsCoach())) {
                studentInfo.setCoachId(coachInfo.getId());
            } else if ("1".equals(studentInfo.getIsCoach())) {
                studentInfo.setLearnId(coachInfo.getId());
            }
        }
        if (StrUtil.isNotEmpty(roleId)) {
            SysRole role = sysRoleMapper.selectRoleById(Long.parseLong(roleId));
            CoachInfo coachInfo = coachInfoMapper.findByUserId(userId.toString());
            if ("合伙人".equals(role.getRoleName())) {
                studentInfo.setStoreUserId(userId.toString());
            } else if ("交付中心".equals(role.getRoleName())) {
                List<PayGroup> groups = payGroupMapper.findUseByUserId(userId.toString());
                studentInfo.setGroups(groups);
            } else if ("学管师".equals(role.getRoleName())) {
                studentInfo.setLearnId(coachInfo.getId());
            } else if ("教练".equals(role.getRoleName())) {
                studentInfo.setCoachId(coachInfo.getId());
            } else if ("交付小组组长".equals(role.getRoleName())) {
                studentInfo.setPayGroupId(coachInfo.getPayGroupId());
            }
        }
        PageUtils.startPage();
        List<StudentInfo> list = studentInfoMapper.selectStudentInfoList(studentInfo);
        for (StudentInfo info : list) {
            setNames(info);
        }
        return list;
    }

    @Override
    public List<StudentInfo> findAll(StudentInfo studentInfo) {
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        if(!"admin".equals(username)){
            String roleId = sysLogininforService.findLoginRoleId(userId.toString());
            if (StrUtil.isNotEmpty(roleId)) {
                SysRole role = sysRoleMapper.selectRoleById(Long.parseLong(roleId));
                if ("合伙人".equals(role.getRoleName())) {
                    studentInfo.setStoreUserId(userId.toString());
                } else if ("交付中心".equals(role.getRoleName())) {
                    List<PayGroup> groups = payGroupMapper.findUseByUserId(userId.toString());
                    studentInfo.setGroups(groups);
                } else if ("学管师".equals(role.getRoleName())) {
                    studentInfo.setLearnId(userId.toString());
                } else if ("教练".equals(role.getRoleName())) {
                    studentInfo.setCoachId(userId.toString());
                } else if ("交付小组组长".equals(role.getRoleName())) {
                    CoachInfo coachInfo = coachInfoMapper.findByUserId(userId.toString());
                    studentInfo.setPayGroupId(coachInfo.getPayGroupId());
                }
            }
        }
        PageUtils.startPage();
        List<StudentInfo> list = studentInfoMapper.selectStudentInfoAll(studentInfo);
        for (StudentInfo info : list) {
            List<StudentInfo> studentInfos = studentInfoMapper.findByUserId(info.getUserId());
            if (!studentInfos.isEmpty()) {
                int buyLearnTime = 0;
                int surplusLearnTime = 0;
                String classType = "";
                String payGroup = "";
                String firstTime = DateUtil.now();
                for (StudentInfo info1 : studentInfos) {
//                    setNames(info1);
                    if (StrUtil.isNotEmpty(info1.getBuyLearnTime())) {
                        buyLearnTime += Integer.parseInt(info1.getBuyLearnTime());
                    }
                    if (StrUtil.isNotEmpty(info1.getSurplusLearnTime())) {
                        surplusLearnTime += Integer.parseInt(info1.getSurplusLearnTime());
                    }
                    if (StrUtil.isNotEmpty(info1.getClassTypeName()) && !classType.contains(info1.getClassTypeName())) {
                        classType += info1.getClassTypeName() + ",";
                    }
                    if (StrUtil.isNotEmpty(info1.getPayGroupName()) && !payGroup.contains(info1.getPayGroupName())) {
                        payGroup += info1.getPayGroupName() + ",";
                    }
                    if (StrUtil.isNotEmpty(info1.getFirstTime())) {
                        int compare = DateUtil.compare(DateUtil.parseDate(info1.getFirstTime()), DateUtil.parseDate(firstTime));
                        if (compare < 0) {
                            firstTime = info1.getFirstTime();
                        }
                    }
                }
                info.setBuyLearnTime(String.valueOf(buyLearnTime));
                info.setSurplusLearnTime(String.valueOf(surplusLearnTime));
                info.setClassTypeName(classType);
                info.setPayGroupName(payGroup);
                info.setFirstTime(firstTime);
            }
        }
        return list;
    }

    public void setNames(StudentInfo info) {
        //支付小组名称
        if (StringUtils.isNotEmpty(info.getPayGroupId())) {
            PayGroup payGroup = payGroupMapper.selectPayGroupById(info.getPayGroupId());
            if (ObjectUtil.isNotEmpty(payGroup)) {
                info.setPayGroupName(payGroup.getName());
            }
        }
        //学管师名称
        if (StringUtils.isNotEmpty(info.getLearnId())) {
            CoachInfo coachInfo = coachInfoMapper.selectCoachInfoById(info.getLearnId());
            if (ObjectUtil.isNotEmpty(coachInfo)) {
                info.setLearnName(coachInfo.getName());
            }
            //交付中心名称-学管的创建人就是交付中心
            SysUser user = sysUserMapper.selectUserById(Long.parseLong(coachInfo.getCreateBy()));
            if (ObjectUtil.isNotEmpty(user)) {
                info.setPayCenterId(user.getUserId().toString());
                info.setPayCenterName(user.getUserName());
            }
        }
        //上课教练名称
        if (StringUtils.isNotEmpty(info.getCoachId())) {
            CoachInfo coachInfo = coachInfoMapper.selectCoachInfoById(info.getCoachId());
            if (ObjectUtil.isNotEmpty(coachInfo)) {
                info.setCoachName(coachInfo.getName());
                info.setTeachMethod(coachInfo.getTeachMethod());
                info.setPosition(coachInfo.getPosition());
            }
        }
    }

    /**
     * 新增学员信息
     *
     * @param studentInfo 学员信息
     * @return 结果
     */
    @Override
    public int add(StudentInfo studentInfo) {
        studentInfo.setId(IdUtil.simpleUUID());
        studentInfo.setDelFlag("0");
        return studentInfoMapper.insert(studentInfo);
    }

    /**
     * 修改学员信息
     *
     * @param studentInfo 学员信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateEntity(StudentInfo studentInfo) {
        try{
            //学习状况反馈-无id版
            if (StringUtils.isNotEmpty(studentInfo.getOrderCode()) && StringUtils.isNotEmpty(studentInfo.getLearnRemark())) {
                StudentInfo student = studentInfoMapper.findByOrderCode(studentInfo.getOrderCode());
                if (ObjectUtil.isNotEmpty(student)) {
                    studentInfo.setId(student.getId());
                }
            }
            //教练接单退单
            if (StringUtils.isNotEmpty(studentInfo.getCoachOrderStatus())) {
                if ("2".equals(studentInfo.getCoachOrderStatus())) {
                    //教练退单
                    //必须是未上过课的订单才能退，退单之后重新发消息到企微群聊
                    List<PlanClass> planClasses = planClassMapper.findByOrder(studentInfo.getOrderCode());
                    if (planClasses.size() == 0) {
                        // 清空教练
                        studentInfo.setCoachId("");
                        StudentInfo existingInfo = studentInfoMapper.selectById(studentInfo.getId());
                        String payGroupId = existingInfo.getPayGroupId();
                        //重新发送派单消息到企微群聊
                        PayGroup payGroup = payGroupMapper.selectPayGroupById(payGroupId);
                        if (ObjectUtil.isNotEmpty(payGroup) && StrUtil.isNotEmpty(payGroup.getBotKey()) && ObjectUtil.isNotEmpty(studentInfo) && StrUtil.isNotEmpty(studentInfo.getId())) {
                            SendQWmsgUtil.sendMsg(existingInfo, payGroup.getBotKey());
                        }
                    } else {
                        throw new RuntimeException("该订单已上过课，不能退单");
                    }
                } else if ("1".equals(studentInfo.getCoachOrderStatus())) {
                    //教练接单
                    //检查是否已经接单
                    if (StringUtils.isNotEmpty(studentInfo.getId())) {
                        StudentInfo existingInfo = studentInfoMapper.selectById(studentInfo.getId());
                        if (ObjectUtil.isNotEmpty(existingInfo) && "1".equals(existingInfo.getCoachOrderStatus())) {
                            throw new RuntimeException("该订单已被接单，不能重复接单");
                        }
                    }

                    String username = SecurityUtils.getUsername();
                    if(!"admin".equals(username)){
                        CoachInfo coachInfo = coachInfoMapper.findByUserId(SecurityUtils.getUserIdStr());
                        if (ObjectUtil.isEmpty(coachInfo)) {
                            throw new RuntimeException("教练信息不存在，请先完善教练信息再接单");
                        }
                        studentInfo.setCoachId(coachInfo.getId());
                        if (StringUtils.isNotEmpty(coachInfo.getLearnId())) {
                            studentInfo.setLearnId(coachInfo.getLearnId());
                        }
                    }


                }
            }
            //学管退课退款
            if (StringUtils.isNotEmpty(studentInfo.getLearnId()) && StringUtils.isNotEmpty(studentInfo.getApprovalStatus()) && "1".equals(studentInfo.getApprovalStatus())) {
                CoachInfo coachInfo = coachInfoMapper.selectCoachInfoById(studentInfo.getLearnId());
                if (ObjectUtil.isNotEmpty(coachInfo)) {
                    SysUser user = sysUserMapper.selectUserById(Long.parseLong(coachInfo.getCreateBy()));
                    if (ObjectUtil.isNotEmpty(user)) {
                        //学管退课-提交审核申请
                        approvalInfoService.add(ApprovalInfo.builder()
                                .businessType("0")
                                .businessId(studentInfo.getId())
                                .appUserId(SecurityUtils.getUserIdStr())
                                .appUserName(SecurityUtils.getUsername())
                                .status("0")
                                .explan(studentInfo.getDropRemark())
                                .approver(coachInfo.getCreateBy())
                                .approverName(user.getUserName())
                                .build());
                    }
                }
            }
            studentInfo.setUpdateTime(DateUtil.date());
            if (StrUtil.isEmpty(studentInfo.getId()) && StrUtil.isNotEmpty(studentInfo.getOrderCode())){
                StudentInfo student = studentInfoMapper.findByOrderCode(studentInfo.getOrderCode());
                if (ObjectUtil.isNotEmpty(student)){
                    studentInfo.setId(student.getId());
                }else {
                    throw new RuntimeException("订单号对应学员不存在");
                }
            }
            return studentInfoMapper.updateById(studentInfo);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


    @Override
    @Transactional
    public int updateEntityTk(StudentInfo studentInfo) {
        try{
            //学习状况反馈-无id版
            if (StringUtils.isNotEmpty(studentInfo.getOrderCode()) && StringUtils.isNotEmpty(studentInfo.getLearnRemark())) {
                StudentInfo student = studentInfoMapper.findByOrderCode(studentInfo.getOrderCode());
                if (ObjectUtil.isNotEmpty(student)) {
                    studentInfo.setId(student.getId());
                }
            }
            //学管退课退款
            if (StringUtils.isNotEmpty(studentInfo.getLearnId()) && StringUtils.isNotEmpty(studentInfo.getApprovalStatus()) && "1".equals(studentInfo.getApprovalStatus())) {
                CoachInfo coachInfo = coachInfoMapper.selectCoachInfoById(studentInfo.getLearnId());
                if (ObjectUtil.isNotEmpty(coachInfo)) {
                    SysUser user = sysUserMapper.selectUserById(Long.parseLong(coachInfo.getCreateBy()));
                    if (ObjectUtil.isNotEmpty(user)) {
                        //学管退课-提交审核申请
                        approvalInfoService.add(ApprovalInfo.builder()
                                .businessType("0")
                                .businessId(studentInfo.getId())
                                .appUserId(SecurityUtils.getUserIdStr())
                                .appUserName(SecurityUtils.getUsername())
                                .status("0")
                                .amount(studentInfo.getSurplusAmount())
                                .explan(studentInfo.getDropRemark())
                                .approver(coachInfo.getCreateBy())
                                .approverName(user.getUserName())
                                .build());
                    }
                }
            }
            studentInfo.setUpdateTime(DateUtil.date());
            if (StrUtil.isEmpty(studentInfo.getId()) && StrUtil.isNotEmpty(studentInfo.getOrderCode())){
                StudentInfo student = studentInfoMapper.findByOrderCode(studentInfo.getOrderCode());
                if (ObjectUtil.isNotEmpty(student)){
                    studentInfo.setId(student.getId());
                }else {
                    throw new RuntimeException("订单号对应学员不存在");
                }
            }
            return studentInfoMapper.updateById(studentInfo);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 分配学管
     *
     * @param ids
     * @param learnId
     * @return
     */
    @Override
    public int setLearnId(List<String> ids, String learnId) {
        return studentInfoMapper.setLearnId(ids, learnId);
    }

    /**
     * 批量删除学员信息
     *
     * @param ids 需要删除的学员信息主键
     * @return 结果
     */
    @Override
    public int deleteIds(List<String> ids) {
        return studentInfoMapper.deleteStudentInfoByIds(ids);
    }

    /**
     * 删除学员信息信息
     *
     * @param id 学员信息主键
     * @return 结果
     */
    @Override
    public int deleteById(String id) {
        return studentInfoMapper.deleteStudentInfoById(id);
    }
}
